<template>
  <div class="checkout-page">
    <div class="container">
      <div class="page-header">
        <h1>确认订单</h1>
        <el-steps :active="currentStep" align-center>
          <el-step title="确认商品" />
          <el-step title="填写信息" />
          <el-step title="支付订单" />
          <el-step title="完成" />
        </el-steps>
      </div>

      <div class="checkout-content">
        <!-- 第一步：确认商品 -->
        <div v-if="currentStep === 0" class="step-content">
          <div class="checkout-main">
            <div class="order-items">
              <h2>商品清单</h2>
              <div class="items-list">
                <div 
                  v-for="item in checkoutItems"
                  :key="`${item.id}-${item.variant?.id || 'default'}`"
                  class="order-item"
                >
                  <div class="item-image">
                    <img :src="item.image" :alt="item.name" />
                  </div>
                  <div class="item-info">
                    <h3>{{ item.name }}</h3>
                    <p v-if="item.variant">规格：{{ item.variant.name }}</p>
                    <p class="item-desc">{{ item.description }}</p>
                  </div>
                  <div class="item-price">
                    <span>¥{{ item.price }}</span>
                  </div>
                  <div class="item-quantity">
                    <span>× {{ item.quantity }}</span>
                  </div>
                  <div class="item-subtotal">
                    <span>¥{{ (item.price * item.quantity).toFixed(2) }}</span>
                  </div>
                </div>
              </div>
            </div>

            <div class="order-summary">
              <h2>订单摘要</h2>
              <div class="summary-content">
                <div class="summary-line">
                  <span>商品总数：</span>
                  <span>{{ totalQuantity }} 件</span>
                </div>
                <div class="summary-line">
                  <span>商品总价：</span>
                  <span>¥{{ subtotal.toFixed(2) }}</span>
                </div>
                <div class="summary-line">
                  <span>运费：</span>
                  <span class="shipping-fee">
                    {{ shippingFee > 0 ? `¥${shippingFee.toFixed(2)}` : '免费' }}
                  </span>
                </div>
                <div v-if="discount > 0" class="summary-line discount">
                  <span>优惠金额：</span>
                  <span>-¥{{ discount.toFixed(2) }}</span>
                </div>
                <div class="summary-line total">
                  <span>应付总额：</span>
                  <span class="total-price">¥{{ totalAmount.toFixed(2) }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="step-actions">
            <el-button @click="$router.push('/cart')">返回购物车</el-button>
            <el-button type="primary" @click="nextStep">确认商品信息</el-button>
          </div>
        </div>

        <!-- 第二步：填写信息 -->
        <div v-if="currentStep === 1" class="step-content">
          <div class="checkout-main">
            <div class="form-section">
              <h2>收货信息</h2>
              <el-form :model="orderForm" :rules="formRules" ref="orderFormRef" label-width="100px">
                <el-form-item label="收货人" prop="name">
                  <el-input v-model="orderForm.name" placeholder="请输入收货人姓名" />
                </el-form-item>
                
                <el-form-item label="手机号码" prop="phone">
                  <el-input v-model="orderForm.phone" placeholder="请输入手机号码" />
                </el-form-item>
                
                <el-form-item label="收货地址" prop="address">
                  <el-input 
                    v-model="orderForm.address" 
                    type="textarea"
                    :rows="3"
                    placeholder="请输入详细地址"
                  />
                </el-form-item>
                
                <el-form-item label="备注">
                  <el-input 
                    v-model="orderForm.note" 
                    type="textarea"
                    :rows="2"
                    placeholder="选填，对订单的补充说明"
                  />
                </el-form-item>
              </el-form>
            </div>

            <div class="delivery-section">
              <h2>配送方式</h2>
              <el-radio-group v-model="selectedDelivery" class="delivery-options">
                <el-radio 
                  v-for="option in deliveryOptions"
                  :key="option.id"
                  :label="option.id"
                  class="delivery-option"
                >
                  <div class="option-info">
                    <div class="option-name">{{ option.name }}</div>
                    <div class="option-desc">{{ option.description }}</div>
                    <div class="option-price">{{ option.price > 0 ? `¥${option.price}` : '免费' }}</div>
                  </div>
                </el-radio>
              </el-radio-group>
            </div>
          </div>

          <div class="step-actions">
            <el-button @click="prevStep">上一步</el-button>
            <el-button type="primary" @click="validateAndNext">确认信息</el-button>
          </div>
        </div>

        <!-- 第三步：支付订单 -->
        <div v-if="currentStep === 2" class="step-content">
          <div class="checkout-main">
            <div class="payment-section">
              <h2>选择支付方式</h2>
              <el-radio-group v-model="selectedPayment" class="payment-options">
                <el-radio 
                  v-for="option in paymentOptions"
                  :key="option.id"
                  :label="option.id"
                  class="payment-option"
                >
                  <div class="payment-info">
                    <el-icon size="24">
                      <component :is="option.icon" />
                    </el-icon>
                    <span class="payment-name">{{ option.name }}</span>
                    <span v-if="option.discount" class="payment-discount">
                      {{ option.discount }}
                    </span>
                  </div>
                </el-radio>
              </el-radio-group>
            </div>

            <div class="order-review">
              <h2>订单确认</h2>
              <div class="review-content">
                <div class="review-section">
                  <h3>收货信息</h3>
                  <p>{{ orderForm.name }} {{ orderForm.phone }}</p>
                  <p>{{ orderForm.address }}</p>
                </div>
                
                <div class="review-section">
                  <h3>商品信息</h3>
                  <p>共 {{ totalQuantity }} 件商品</p>
                </div>
                
                <div class="review-section">
                  <h3>支付金额</h3>
                  <p class="final-amount">¥{{ totalAmount.toFixed(2) }}</p>
                </div>
              </div>
            </div>
          </div>

          <div class="step-actions">
            <el-button @click="prevStep">上一步</el-button>
            <el-button type="primary" @click="submitOrder" :loading="isSubmitting">
              确认支付
            </el-button>
          </div>
        </div>

        <!-- 第四步：完成 -->
        <div v-if="currentStep === 3" class="step-content">
          <div class="success-content">
            <el-result icon="success" title="订单提交成功" sub-title="感谢您的购买，我们会尽快为您发货">
              <template #extra>
                <div class="success-info">
                  <p><strong>订单号：</strong>{{ orderNumber }}</p>
                  <p><strong>支付金额：</strong>¥{{ totalAmount.toFixed(2) }}</p>
                  <p><strong>预计送达：</strong>{{ estimatedDelivery }}</p>
                </div>
                <div class="success-actions">
                  <el-button type="primary" @click="$router.push('/')">返回首页</el-button>
                  <el-button @click="$router.push('/products')">继续购物</el-button>
                </div>
              </template>
            </el-result>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { store } from '@/store'
import { ElMessage } from 'element-plus'
import { 
  CreditCard,
  Cellphone,
  Wallet
} from '@element-plus/icons-vue'

export default {
  name: 'CheckoutPage',
  components: {
    CreditCard,
    Cellphone,
    Wallet
  },
  setup() {
    const router = useRouter()
    const orderFormRef = ref(null)
    
    // 步骤控制
    const currentStep = ref(0)
    
    // 订单商品（从购物车或路由状态获取）
    const checkoutItems = ref([])
    
    // 表单数据
    const orderForm = ref({
      name: '',
      phone: '',
      address: '',
      note: ''
    })
    
    // 配送选项
    const selectedDelivery = ref(1)
    const deliveryOptions = ref([
      {
        id: 1,
        name: '普通快递',
        description: '3-5个工作日送达',
        price: 0 // 免费
      },
      {
        id: 2,
        name: '加急配送',
        description: '1-2个工作日送达',
        price: 15
      },
      {
        id: 3,
        name: '次日达',
        description: '次日送达（限同城）',
        price: 25
      }
    ])
    
    // 支付选项
    const selectedPayment = ref(1)
    const paymentOptions = ref([
      {
        id: 1,
        name: '微信支付',
        icon: 'Cellphone',
        discount: ''
      },
      {
        id: 2,
        name: '支付宝',
        icon: 'Wallet',
        discount: ''
      },
      {
        id: 3,
        name: '银行卡支付',
        icon: 'CreditCard',
        discount: '首次使用立减5元'
      }
    ])
    
    // 订单状态
    const isSubmitting = ref(false)
    const orderNumber = ref('')
    
    // 表单验证规则
    const formRules = {
      name: [
        { required: true, message: '请输入收货人姓名', trigger: 'blur' },
        { min: 2, max: 10, message: '姓名长度在2到10个字符', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      address: [
        { required: true, message: '请输入收货地址', trigger: 'blur' },
        { min: 10, message: '请输入详细的收货地址', trigger: 'blur' }
      ]
    }
    
    // 计算属性
    const totalQuantity = computed(() => {
      return checkoutItems.value.reduce((total, item) => total + item.quantity, 0)
    })
    
    const subtotal = computed(() => {
      return checkoutItems.value.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
    })
    
    const shippingFee = computed(() => {
      const delivery = deliveryOptions.value.find(d => d.id === selectedDelivery.value)
      return delivery ? delivery.price : 0
    })
    
    const discount = computed(() => {
      // 模拟优惠计算
      if (subtotal.value >= 200) {
        return 10 // 满200减10
      }
      return 0
    })
    
    const totalAmount = computed(() => {
      return subtotal.value + shippingFee.value - discount.value
    })
    
    const estimatedDelivery = computed(() => {
      const delivery = deliveryOptions.value.find(d => d.id === selectedDelivery.value)
      const days = delivery?.id === 1 ? 5 : delivery?.id === 2 ? 2 : 1
      const date = new Date()
      date.setDate(date.getDate() + days)
      return date.toLocaleDateString('zh-CN')
    })
    
    // 方法
    const initCheckoutData = () => {
      // 从购物车获取选中的商品
      const selectedItems = store.cart.items.filter(item => item.selected !== false)
      
      if (selectedItems.length === 0) {
        ElMessage.warning('没有选择商品，返回购物车')
        router.push('/cart')
        return
      }
      
      checkoutItems.value = selectedItems.map(item => ({
        ...item,
        subtotal: item.price * item.quantity
      }))
    }
    
    const nextStep = () => {
      if (currentStep.value < 3) {
        currentStep.value++
      }
    }
    
    const prevStep = () => {
      if (currentStep.value > 0) {
        currentStep.value--
      }
    }
    
    const validateAndNext = async () => {
      try {
        await orderFormRef.value.validate()
        nextStep()
      } catch (error) {
        ElMessage.error('请填写完整的订单信息')
      }
    }
    
    const generateOrderNumber = () => {
      const timestamp = Date.now()
      const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
      return `PET${timestamp}${random}`
    }
    
    const submitOrder = async () => {
      isSubmitting.value = true
      
      try {
        // 模拟提交订单
        await new Promise(resolve => setTimeout(resolve, 2000))
        
        // 生成订单号
        orderNumber.value = generateOrderNumber()
        
        // 清空购物车中的已选商品
        checkoutItems.value.forEach(item => {
          store.removeFromCart(item.id)
        })
        
        // 进入成功页面
        nextStep()
        
        ElMessage.success('订单提交成功')
      } catch (error) {
        ElMessage.error('订单提交失败，请重试')
      } finally {
        isSubmitting.value = false
      }
    }
    
    onMounted(() => {
      initCheckoutData()
    })
    
    return {
      currentStep,
      checkoutItems,
      orderForm,
      orderFormRef,
      formRules,
      selectedDelivery,
      deliveryOptions,
      selectedPayment,
      paymentOptions,
      isSubmitting,
      orderNumber,
      totalQuantity,
      subtotal,
      shippingFee,
      discount,
      totalAmount,
      estimatedDelivery,
      nextStep,
      prevStep,
      validateAndNext,
      submitOrder,
      // Element Plus icons
      CreditCard,
      Cellphone,
      Wallet
    }
  }
}
</script>

<style scoped>
.checkout-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 30px 0;
}

.page-header {
  background: white;
  padding: 40px;
  margin-bottom: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.page-header h1 {
  text-align: center;
  font-size: 2rem;
  color: #333;
  margin-bottom: 30px;
}

.checkout-content {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.step-content {
  padding: 40px;
}

.checkout-main {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 40px;
  margin-bottom: 40px;
}

/* 订单商品列表 */
.order-items h2,
.order-summary h2,
.form-section h2,
.delivery-section h2,
.payment-section h2,
.order-review h2 {
  font-size: 1.3rem;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #f0f0f0;
}

.items-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.order-item {
  display: grid;
  grid-template-columns: 80px 1fr 100px 80px 120px;
  gap: 15px;
  align-items: center;
  padding: 15px;
  background: #fafafa;
  border-radius: 8px;
}

.item-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info h3 {
  font-size: 1rem;
  color: #333;
  margin-bottom: 5px;
}

.item-info p {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 3px;
}

.item-desc {
  font-size: 0.8rem !important;
  color: #999 !important;
}

.item-price,
.item-quantity,
.item-subtotal {
  text-align: center;
  font-weight: 500;
}

.item-subtotal {
  color: #f56565;
  font-weight: 600;
}

/* 订单摘要 */
.summary-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.summary-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.summary-line.discount {
  color: #FFB300;
}

.summary-line.total {
  font-size: 1.2rem;
  font-weight: bold;
  padding-top: 15px;
  border-top: 1px solid #eee;
  margin-top: 10px;
}

.total-price {
  color: #f56565;
  font-size: 1.5rem;
}

.shipping-fee {
  color: #FFB300;
}

/* 表单部分 */
.form-section,
.delivery-section,
.payment-section {
  grid-column: 1 / -1;
  margin-bottom: 30px;
}

.delivery-options,
.payment-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.delivery-option,
.payment-option {
  width: 100%;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
  margin: 0;
  transition: all 0.3s ease;
}

.delivery-option:hover,
.payment-option:hover {
  border-color: #FF8C00;
  background: #f0f9ff;
}

.option-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-left: 10px;
}

.option-name {
  font-weight: 600;
  color: #333;
}

.option-desc {
  color: #666;
  font-size: 0.9rem;
}

.option-price {
  color: #f56565;
  font-weight: 600;
}

.payment-info {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-left: 10px;
}

.payment-name {
  font-weight: 600;
  color: #333;
  flex: 1;
}

.payment-discount {
  color: #FFB300;
  font-size: 0.9rem;
}

/* 订单确认 */
.order-review {
  grid-column: 1 / -1;
}

.review-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 30px;
}

.review-section h3 {
  font-size: 1rem;
  color: #333;
  margin-bottom: 10px;
}

.review-section p {
  color: #666;
  line-height: 1.5;
}

.final-amount {
  font-size: 1.5rem !important;
  font-weight: bold !important;
  color: #f56565 !important;
}

/* 步骤操作 */
.step-actions {
  display: flex;
  justify-content: space-between;
  padding-top: 30px;
  border-top: 1px solid #eee;
}

/* 成功页面 */
.success-content {
  text-align: center;
  padding: 40px;
}

.success-info {
  margin: 30px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.success-info p {
  margin-bottom: 10px;
  font-size: 1.1rem;
}

.success-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .checkout-main {
    grid-template-columns: 1fr;
    gap: 30px;
  }
  
  .order-item {
    grid-template-columns: 60px 1fr 80px 60px 100px;
    gap: 10px;
  }
  
  .item-image {
    width: 60px;
    height: 60px;
  }
}

@media (max-width: 768px) {
  .checkout-page {
    padding: 20px 0;
  }
  
  .page-header,
  .step-content {
    padding: 20px;
  }
  
  .order-item {
    grid-template-columns: 1fr;
    gap: 10px;
    text-align: center;
  }
  
  .item-info {
    order: 1;
  }
  
  .item-image {
    order: 0;
    width: 80px;
    height: 80px;
    justify-self: center;
  }
  
  .option-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .review-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .step-actions {
    flex-direction: column;
    gap: 15px;
  }
  
  .step-actions .el-button {
    width: 100%;
  }
  
  .success-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .success-actions .el-button {
    width: 200px;
  }
}

/* 深度选择器样式 */
:deep(.el-steps) {
  margin-bottom: 0;
}

:deep(.el-radio) {
  width: 100%;
  height: auto;
}

:deep(.el-radio__input) {
  align-self: flex-start;
  margin-top: 5px;
}
</style>
